import mongoose from 'mongoose';
import { DBHOST, DBPORT, DBNAME, DBUSER, DBPWD } from '../config/config';

/**
 * 数据库，使用单例模式
 */
class Database {
    private static instance: Database;
    private isConnected: boolean = false;

    private constructor() {
        // 私有构造函数，防止外部实例化
    }

    /**
     * 获取数据库连接的单例实例
     * @returns Database 实例
     */
    public static getInstance(): Database {
        if (!Database.instance) {
            Database.instance = new Database();
        }
        return Database.instance;
    }

    /**
     * 连接数据库
     * @param success 数据库连接成功的回调
     * @param err 数据库连接失败的回调
     */
    public connect(
        success: () => void,
        err: () => void = () => console.log("数据库连接失败")
    ): void {
        if (this.isConnected) {
            console.log("数据库已连接");
            success();
            return;
        }

        mongoose.connect(`mongodb://${DBUSER}:${DBPWD}@${DBHOST}:${DBPORT}/${DBNAME}`);

        // 设置回调
        // 连接成功的回调 once: 事件只执行一次
        mongoose.connection.once('open', () => {
            this.isConnected = true;
            success();
        });

        // 连接错误的回调
        mongoose.connection.on('error', () => {
            err();
        });

        // 连接关闭的回调
        mongoose.connection.on('close', () => {
            this.isConnected = false;
            console.log("连接关闭");
        });
    }

    /**
     * 断开数据库连接
     */
    public disconnect(): void {
        if (this.isConnected) {
            mongoose.connection.close();
            this.isConnected = false;
            console.log("数据库连接已断开");
        } else {
            console.log("数据库未连接");
        }
    }
}

export default Database;
